package com.wecon.dianping.service.impl;

import com.wecon.dianping.common.BusinessException;
import com.wecon.dianping.common.EmBusinessError;
import com.wecon.dianping.dal.CategoryMapper;
import com.wecon.dianping.model.Category;
import com.wecon.dianping.model.CategoryExample;
import com.wecon.dianping.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Weikang  Wang
 * @program: com.wecon.dianping.service.impl
 * @description: 品类管理服务层
 * @date 2020/3/17 16:27
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    @Transactional
    public Category create(Category category) throws BusinessException {

        // 判断品列名称是否唯一
        try {
            categoryMapper.insertSelective(category);
        } catch (DuplicateKeyException e) {
           throw new BusinessException(EmBusinessError.CATEGORY_NAME_DUPLICATED);
        }

        return getCategory(category.getId());
    }

    @Override
    public Category getCategory(Integer id) {
        return categoryMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Category> selectAll() {
        return categoryMapper.selectAll();
    }

    /**
     * 获取品类数量
     * @return /
     */
    @Override
    public Integer countAllCategory() {
        CategoryExample example = new CategoryExample();
        example.or().andIdGreaterThan(0);
        return categoryMapper.countByExample(example);
    }
}
